﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ProgrammLauncher.cs" >
//   J. Prinz
// </copyright>
// <summary>
//   This Static Class supports launching a Programm registred to view or edit any file with a file-extension
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace AutomationMLMapper.Utilities
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Windows;

    using Microsoft.Win32;

    /// <summary>
    ///   This Static Class supports launching a Programm registred to view or edit any file with a file-extension
    /// </summary>
    public static class ProgrammLauncher
    {
        #region Public Methods and Operators

        /// <summary>
        /// Launch an application registred with the files extension to view/edit this file.
        /// </summary>
        /// <param name="filePath">
        /// File Full-Path 
        /// </param>
        /// <returns>
        /// The System.Boolean. 
        /// </returns>
        public static bool Launch(string filePath)
        {
            try
            {
                var executable = new Process();

                string applicationName;
                var shellApplicationName = string.Empty;
                var fileExtension = Path.GetExtension(filePath);
                var paramFileName = filePath;

                // ShellApplicationName = @"C:\Program Files (x86)\AutomationML\AutomationML Editor\AMLEditor.exe";
                if (!string.IsNullOrEmpty(shellApplicationName)
                    ||
                    GetRegisteredApplication(
                        paramFileName, fileExtension, out applicationName, out shellApplicationName))
                {
                    var splits = shellApplicationName.Split(
                        new[] { ".exe", "\"" }, StringSplitOptions.RemoveEmptyEntries);

                    shellApplicationName = splits[0] + ".exe";

                    executable.StartInfo.FileName = shellApplicationName;
                    executable.StartInfo.Arguments = "\"" + filePath + "\"";
                    executable.StartInfo.UseShellExecute = false;
                    executable.Start();

                    return true;
                }

                MessageBox.Show(
                    "Couldn't find any registred programm to open file", 
                    "Mapping Tool Warning", 
                    MessageBoxButton.OK, 
                    MessageBoxImage.Warning);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Mapping Tool Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            return false;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Get the registered application.
        /// </summary>
        /// <param name="paramFileName">
        /// The file name. 
        /// </param>
        /// <param name="fileExtension">
        /// The file extension. 
        /// </param>
        /// <param name="appName">
        /// The app name. 
        /// </param>
        /// <param name="shellAppName">
        /// The shell app name. 
        /// </param>
        /// <returns>
        /// The System.Boolean. 
        /// </returns>
        private static bool GetRegisteredApplication(
            string paramFileName, string fileExtension, out string appName, out string shellAppName)
        {
            appName = string.Empty;
            shellAppName = string.Empty;

            try
            {
                // Add starting dot to extension
                var strExt = fileExtension;

                // Get Programmatic Identifier for this extension
                var strProgID = string.Empty;
                RegistryKey keyOHKCR;
                try
                {
                    keyOHKCR = Registry.ClassesRoot;
                    var progID = keyOHKCR.OpenSubKey(strExt);
                    if (progID != null)
                    {
                        strProgID = progID.GetValue(null).ToString();
                        progID.Close();
                    }
                }
                catch
                {
                    // No ProgID, return false
                    return false;
                }

                // Get associated application
                var strExe = string.Empty;
                try
                {
                    var openCmd = keyOHKCR.OpenSubKey(strProgID + "\\shell\\open\\command");
                    if (openCmd != null)
                    {
                        strExe = openCmd.GetValue(null).ToString();
                        openCmd.Close();
                    }
                }
                catch
                {
                    // Missing default application
                    return false;
                }

                var tempPos = strExe.IndexOf("%1", StringComparison.Ordinal);
                if (tempPos > 0)
                {
                    // Replace %1 placeholder with ParamFileName
                    strExe = strExe.Substring(0, tempPos);
                    appName = strExe;

                    // StrExe = StrExe + " " + Convert.ToChar(34) + ParamFileName + Convert.ToChar(34);
                    strExe = strExe + " " + paramFileName;
                    shellAppName = strExe;
                }
                else
                {
                    // No %1 placeholder found, append ParamFileName
                    appName = strExe;
                    shellAppName = strExe + " " + Convert.ToChar(34) + paramFileName + Convert.ToChar(34);
                }

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "error", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
        }

        #endregion
    }
}